#include "onlineconnector.h"

OnlineConnector::OnlineConnector(QStatusBar *statusbar, QObject *parent) :
    QObject(parent)
{
    mManager = new QNetworkAccessManager(this);
    mManager->setCookieJar(new QNetworkCookieJar(this));

    mReply = 0;

    login_progress_label = new QLabel();
    login_progress_bar = new QProgressBar();

    logedIn = session_cookies.isEmpty()?false:true;
    this->statusbar = statusbar;

    db = QSqlDatabase::database();
    if ( db.isOpen() || db.open() )
    {
        db.transaction();
        QSqlQuery q(db);
        q.prepare("SELECT value FROM data WHERE data = 'online_username';");
        if ( q.exec() && q.first() )
        {
            username = q.value(0).toString();
        }
        q.prepare("SELECT value FROM data WHERE data = 'online_password';");
        if ( q.exec() && q.first() )
        {
            password = q.value(0).toString();
        }
        q.finish();
        db.commit();

        if ( isValid() )
        {
            emit login_valid();
            login();
        }
    }
}

void OnlineConnector::login()
{
    if ( logedIn )
        emit login_success();
    else
    {
        login_progress_label->setText(tr("Login..."));
        login_progress_bar->setRange(0,0);
        login_progress_bar->setTextVisible(false);
        login_progress_bar->setFixedWidth(100);
        statusbar->addPermanentWidget(login_progress_label);
        statusbar->addPermanentWidget(login_progress_bar);
        login_progress_label->show();
        login_progress_bar->show();

        QByteArray data;
        data.append(QString("username=%1&password=%2").arg(username, password));
        mUrl = QUrl("http://www.leverdy.de/login.php");
        QNetworkRequest r(mUrl);
        r.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
        mReply = mManager->post(r, data);
        connect(mReply, SIGNAL(finished()), this, SLOT(replyFinished()));
    }
}

void OnlineConnector::replyFinished()
{
    statusbar->removeWidget(login_progress_label);
    statusbar->removeWidget(login_progress_bar);

    if (mReply->error() != QNetworkReply::NoError){
        QMessageBox::warning(0, tr("Online Verbindung"), tr("Login fehlgeschlagen: ") + mReply->errorString() );
        emit login_failed(mReply->errorString());
        return;
    }

    foreach ( QNetworkCookie c, mManager->cookieJar()->cookiesForUrl(mUrl) )
    {
        if ( c.name() == "PHPSESSID" )
        {
            session_cookies = mManager->cookieJar()->cookiesForUrl(mUrl);
            logedIn = true;
            emit login_valid();
            emit login_success();
            statusbar->showMessage(tr("Login erfolgreich"), 5000);
            return;
        }
    }

    emit login_failed();
}

void OnlineConnector::setPassword(const QString &value)
{
    password = value;
}

bool OnlineConnector::isValid() const
{
    return ( !username.isEmpty() && !password.isEmpty() );
}

QNetworkAccessManager *OnlineConnector::getManager() const
{
    return mManager;
}

QList<QNetworkCookie> OnlineConnector::getCookies() const
{
    return session_cookies;
}

void OnlineConnector::reconnect()
{
    if ( mReply )
        mReply->abort();
    mManager = new QNetworkAccessManager(this);
    mManager->setCookieJar(new QNetworkCookieJar(this));
    logedIn = false;

    if ( isValid() )
        login();
}

void OnlineConnector::setUsername(const QString &value)
{
    username = value;
}


bool OnlineConnector::isLogedIn() const
{
    return logedIn;
}
